package com.usefullc.crawler.component;

import com.usefullc.common.util.jdbc.DataSourceConfig;
import com.usefullc.common.util.jdbc.JdbcUtils;
import com.usefullc.crawler.domain.OutputTemplate;
import com.usefullc.crawler.enums.DatabaseTypeEnum;
import com.usefullc.crawler.service.OutputTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据库组件
 * @author: Sampson
 * @date: 2022-12-15 16:27
 */
@Component
public class DatabaseComponent {

    @Autowired
    private OutputTemplateService outputTemplateService;

    public int send(Long outputTemplateId,Integer databaseType,String sql){
        OutputTemplate outputTemplate = outputTemplateService.findById(outputTemplateId);
        DatabaseTypeEnum databaseTypeEnum = DatabaseTypeEnum.getByCode(databaseType);
        int result = 0;
        switch (databaseTypeEnum){
            case MYSQL:MYSQL:result = mysql(outputTemplate,sql);break;
            default:break;
        }
        return result;
    }


    private int mysql(OutputTemplate outputTemplate,String sql){
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbName(outputTemplate.getName());
        dataSourceConfig.setUrl(outputTemplate.getUrl());
        dataSourceConfig.setDriver("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUser(outputTemplate.getUser());
        dataSourceConfig.setPassword(outputTemplate.getPassword());
        return JdbcUtils.execute(dataSourceConfig,sql);
    }


}
